import React, { useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, message, Upload, Modal } from 'antd';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { getBase64 } from '@/utils/utils';
import type { ConnectState } from '@/models/connect';
import type { CurrentUser } from './components/data';
import { PlusOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import { createUser } from '@/services/user';
import { UPLOAD_IMAGE_URL } from '@/configs/global';
const ManageUser: React.FC = () => {
  const [previewVisible, setPreviewVisible] = useState<boolean>(false);
  const [previewImage, setPreviewImage] = useState<string>('');
  const [previewTitle, setPreviewTitle] = useState<string>('');
  const [fileList, setFileList] = useState<any[]>([]);
  const [form] = ProForm.useForm();

  const handleCancel = () => setPreviewVisible(false);

  const handlePreview = async (file: any) => {
    setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
    setPreviewVisible(true);
  };

  const handleChangeFile = async (val: any) => {
    setFileList(val?.fileList);
    const { file } = val;
    const { status } = file;
    if (status === 'done') {
      if (!file.url && !file.preview) {
        // eslint-disable-next-line no-param-reassign
        file.preview = await getBase64(file.originFileObj);
      }
      setPreviewImage(file.url || file.preview);
    } else {
      setPreviewImage('');
    }
  };

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  return (
    <PageContainer>
      <Card>
        <h3>编辑个人信息</h3>
        <ProForm<CurrentUser>
          form={form}
          layout="horizontal"
          labelCol={{ span: 2 }}
          validateTrigger={['onChange', 'onFocus', 'onBlur']}
          initialValues={{
            roleName: 'user',
          }}
          submitter={{
            // 配置按钮的属性
            resetButtonProps: {
              style: {
                // 隐藏重置按钮
                marginLeft: '50px',
              },
            },
          }}
          onFinish={async (values) => {
            const getAvatar = () => {
              if (values?.avatar?.file?.preview) {
                return values?.avatar?.file.preview;
              }
              return values?.avatar?.fileList?.length === 0 ? '' : values?.avatar;
            };
            const val = values?.avatar
              ? {
                  ...values,
                  avatar: getAvatar(),
                }
              : values;
            const res = await createUser(val);
            message.success(res.message);
          }}
          params={{}}
        >
          <ProFormText
            width="md"
            name="userName"
            label="用户名"
            hasFeedback
            placeholder="请输入用户名"
            rules={[
              {
                required: true,
                message: '用户名不能为空',
              },
            ]}
          />
          <ProFormText
            width="md"
            name="phonenumber"
            hasFeedback
            label="手机号"
            placeholder="请输入手机号"
            validateFirst
            rules={[
              {
                required: false,
              },
              {
                validator: (rule, value) => {
                  const match = /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
                  if (!match.test(value)) {
                    return Promise.reject(new Error('手机号格式不正确！'));
                  }
                  return Promise.resolve();
                },
              },
            ]}
          />

          <ProFormText.Password
            width="md"
            name="password"
            label="密码"
            hasFeedback
            placeholder="请输入密码"
            help="密码包含 数字,英文,字符中的两种以上，长度6-20"
            validateFirst
            rules={[
              {
                required: true,
                message: '密码不能为空',
              },
              {
                validator: (rule, value) => {
                  const match = /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$).{6,20}$/;
                  if (!match.test(value)) {
                    return Promise.reject(
                      new Error('密码包含 数字,英文,字符中的两种以上，长度6-20'),
                    );
                  }
                  return Promise.resolve();
                },
              },
            ]}
          />
          <ProFormText.Password
            width="md"
            name="confirm"
            label="确认密码"
            hasFeedback
            placeholder="请再次输入密码"
            validateFirst
            rules={[
              {
                required: true,
                message: '确认密码不能为空',
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }

                  return Promise.reject(new Error('两次密码不相同!'));
                },
              }),
            ]}
          />
          <ProForm.Item label="头像" name="avatar">
            <Upload
              fileList={fileList}
              action={UPLOAD_IMAGE_URL}
              maxCount={1}
              listType="picture-card"
              onPreview={handlePreview}
              onChange={handleChangeFile}
            >
              {!previewImage && uploadButton}
            </Upload>
          </ProForm.Item>
        </ProForm>
        <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={handleCancel}>
          <img alt="头像" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </Card>
    </PageContainer>
  );
};
export default connect(({ user }: ConnectState) => ({
  currentUser: user.currentUser,
}))(ManageUser);
